<template>
  <div class="user-page">
    <!-- 用户信息区域 -->
    <div class="user-info">
      <div class="avatar-box">
        <van-image
          round
          width="50"
          height="50"
          :src="userInfo.pic || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'"
          @click="showAvatarPopup"
        />
        <div class="user-detail">
          <span class="user-phone">{{ showPhone ? userInfo.mobile : formatPhone(userInfo.mobile) }}</span>
        </div>
      </div>
      <van-icon 
        :name="showPhone ? 'eye-o' : 'closed-eye'" 
        size="20" 
        color="#666" 
        @click="togglePhone"
      />
      <van-icon name="setting-o" size="25" color="#666" class="setting-icon" @click="toSetting"/>
    </div>
    
    <!-- 钱包区域 -->
    <div class="wallet-card" @click="toWallet">
      <div class="wallet-title">钱包中心</div>
      <div class="wallet-amount">{{ userInfo.balance || '0.00' }}</div>
      <van-icon name="arrow" class="arrow-icon" />
    </div>

    <!-- 订单区域 -->
    <div class="order-section">
      <div class="section-header">
        <span>我的订单</span>
        <div class="view-all" @click="viewAllOrders">
          <span>全部</span>
          <van-icon name="arrow" />
        </div>
      </div>
      <div class="order-types">
        <div class="order-type-item" @click="toOrderList(1)">
          <van-icon name="balance-pay" />
          <span>待付款</span>
        </div>
        <div class="order-type-item" @click="toOrderList(2)">
          <van-icon name="send-gift-o" />
          <span>待发货</span>
        </div>
        <div class="order-type-item" @click="toOrderList(3)">
          <van-icon name="logistics" />
          <span>待收货</span>
        </div>
        <div class="order-type-item" @click="toOrderList(4)">
          <van-icon name="comment-o" />
          <span>待评价</span>
        </div>
        <div class="order-type-item" @click="toOrderList(5)">
          <van-icon name="service-o" />
          <span>售后</span>
        </div>
      </div>
    </div>

    <!-- 功能列表 -->
    <div class="feature-list">
      <van-cell-group>
        <van-cell is-link @click="toMyCollection">
          <template #title>
            <van-icon name="award-o" class="feature-icon"/>
            我的藏品
          </template>
        </van-cell>
        <van-cell is-link>
          <template #title>
            <van-icon name="points" class="feature-icon"/>
            打赏积分
          </template>
          <template #value>10000积分</template>
        </van-cell>
        <van-cell is-link>
          <template #title>
            <van-icon name="star-o" class="feature-icon"/>
            收藏夹
          </template>
        </van-cell>
        <van-cell is-link>
          <template #title>
            <van-icon name="like-o" class="feature-icon"/>
            我的关注
          </template>
        </van-cell>
        
        <van-cell is-link>
          <template #title>
            <van-icon name="service-o" class="feature-icon"/>
            客服中心
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <!-- 推荐区域 -->
    <div class="recommend-section">
      <div class="section-title">为你推荐</div>
      <div class="recommend-list">
        <div class="recommend-item" v-for="item in recommendList" :key="item.id" @click="toDetail(item)">
          <van-image
            :src="item.image"
            width="100%"
            height="120"
            fit="cover"
          />
          <div class="item-title">{{ item.title }}</div>
          <div class="item-price">¥{{ item.price }}</div>
        </div>
      </div>
    </div>

    <!-- 头像上传弹出层 -->
    <van-popup v-model:show="showUploader" position="bottom" round>
      <div class="upload-header">
        <span>更换头像</span>
        <van-icon name="cross" @click="showUploader = false" />
      </div>
      <div class="upload-actions">
        <div class="action-item" @click="takePhoto">
          <van-icon name="photograph" />
          <span>拍照</span>
        </div>
        <div class="action-item" @click="choosePhoto">
          <van-icon name="photo" />
          <span>相册</span>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { uploadImage, deleteFile } from '@/api/minio/minio'
import { updateUserPic } from '@/api/user/user'
import { showToast } from 'vant'
import { tim, TIM } from '@/tim'

const router = useRouter()
const userInfo = ref({})
const currentUserID = ref('')

// 头像上传相关
const showUploader = ref(false)
const fileList = ref([])

// 添加手机号显示控制
const showPhone = ref(false)

// 设置页面跳转
const toSetting = () => {
  router.push('/settings')
}

// 获取用户信息
onMounted(async () => {
  try {  
    // 获取本地存储的用户信息
    const userStr = sessionStorage.getItem('user')
    if (userStr) {
      userInfo.value = JSON.parse(userStr)
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
})

// 格式化手机号
const formatPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 模拟推荐数据
const recommendList = ref([
  {
    id: 1,
    title: '六方笑樱 国高工冯盎军 文革泥 350CC',
    price: '1500',
    image: 'https://img0.baidu.com/it/u=2028084904,3939052004&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
  },
  {
    id: 2,
    title: '六方笑樱 国高工冯盎军 文革泥 350CC',
    price: '1500',
    image: 'https://img0.baidu.com/it/u=2028084904,3939052004&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
  }
])

// 页面跳转方法
const toWallet = () => {
  router.push('/wallet')
}

const viewAllOrders = () => {
  router.push('/orders')
}

const toOrderList = (status) => {
  router.push({
    path: '/orders',
    query: { status }
  })
}

const toMyCollection = () => {
  router.push('/collection')
}

const toDetail = (item) => {
  router.push({
    path: '/detail',
    query: { id: item.id }
  })
}

const showAvatarPopup = () => {
  showUploader.value = true
}

const afterRead = async (file) => {
  try {
    // 直接传文件对象，而不是 {file: file.file}
    let res = await uploadImage(file.file, (progress) => {
    })
    
    if (res.code === 200) {
      userInfo.value.pic = res.data
      let res2 = await updateUserPic({id: userInfo.value.id, pic: res.data})
      if (res2.code === 200) {
        showToast('头像上传成功')
        sessionStorage.setItem('user', JSON.stringify(userInfo.value))
      } else {
        showToast(res2.data.message || '更新失败')
      }
    } else {
      showToast(res.data.message || '上传失败')
    }
  } catch (error) {
    showToast('上传失败')
    // console.error(error)
  }
  showUploader.value = false
}

// 跳转到个人信息页
const toUserInfo = () => {
  router.push('/user-info')
}

// 拍照功能
const takePhoto = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.capture = 'camera' // 指定使用相机
  input.onchange = (event) => {
    const file = event.target.files[0]
    if (file) {
      afterRead({ file })
    }
  }
  input.click()
  showUploader.value = false
}

// 选���照片功能
const choosePhoto = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.multiple = false // 只允许选择一张图片
  input.onchange = (event) => {
    const file = event.target.files[0]
    if (file) {
      afterRead({ file })
    }
  }
  input.click()
  showUploader.value = false
}

// 切换手机号显示/隐藏
const togglePhone = () => {
  showPhone.value = !showPhone.value
}
</script>

<style scoped>
.user-page {
  background: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 50px;
}

.user-info {
  height: 60px;
  margin: 40px 20px 10px 20px;
  background: #fff;
  display: flex;
  justify-content: left;
  align-items: center;
}

.avatar-box {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-detail {
  display: flex;
  flex-direction: column;
  gap: 4px;
  cursor: pointer;
}

.user-phone {
  font-size: 16px;
  font-weight: 500;
  margin-right: 20px;
}

.setting-icon {
  position: absolute;
  right: 20px;
  top:20px;
}

.wallet-card {
  margin: 12px;
  background: #c8161d;
  color: #fff;
  padding: 16px;
  border-radius: 8px;
  position: relative;
}

.wallet-title {
  font-size: 14px;
}

.wallet-amount {
  font-size: 24px;
  font-weight: bold;
  margin-top: 8px;
}

.arrow-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
}

.order-section {
  margin-top: 12px;
  background: #fff;
  padding: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-all {
  color: #999;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.order-types {
  display: flex;
  justify-content: space-between;
}

.order-type-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #323233;
}

.order-type-item .van-icon {
  font-size: 24px;
}

.feature-list {
  margin-top: 12px;
}

.recommend-section {
  margin-top: 12px;
  padding: 16px;
  background: #fff;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.recommend-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.recommend-item {
  background: #fff;
}

.item-title {
  font-size: 14px;
  margin: 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-price {
  color: #c8161d;
  font-size: 16px;
  font-weight: 500;
}

/* 添加图标样式 */
.feature-icon {
  font-size: 18px;
  margin-right: 8px;
  vertical-align: -3px;
}

.avatar-box .van-image {
  cursor: pointer;
}

.user-detail {
  cursor: pointer;
}

.upload-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.upload-actions {
  display: flex;
  justify-content: center;
  padding: 40px 20px;
  gap: 80px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #323233;
  cursor: pointer;
}

.action-item .van-icon {
  font-size: 28px;
  color: #1989fa;
}

.user-info .van-icon {
  cursor: pointer;
}
</style>

